package nkr1pt.popkorn.download;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nkr1pt.popkorn.properties.PropertyLoader;

/**
 *
 * @author Kristof Vanhaeren
 */
public class Rapidshare {

    private PropertyLoader propertyLoader;
    private String login;
    private String password;

    public Rapidshare(PropertyLoader propertyLoader) {
        this.propertyLoader = propertyLoader;
        login = propertyLoader.getProperties().getRapidshareLogin();
        password = propertyLoader.getProperties().getRapidsharePassword();
    }


    public String getCookie() throws Exception {
        try {
            return doAPIAuthentication();
        } catch (Exception e) {
            throw new Exception("Could not retrieve an authentication cookie from Rapidshare. Please verify 'rapidshare.login' and 'rapidshare.password' in popkorn.properties");
        }
    }
    
    private String doAPIAuthentication() throws Exception {
//        CertificateInstaller.install("ssl.rapidshare.com", 443, propertyLoader.getProperties().getKeystorePassword());
        URL url = new URL("http://api.rapidshare.com/cgi-bin/rsapi.cgi?");
        String params = "sub=getaccountdetails_v1&withcookie=1&type=prem&login=" + login + "&password=" + password;
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(params);
        writer.close();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {}

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        Pattern pattern = Pattern.compile("cookie=");
        String cookie = null;
        while ((line = reader.readLine()) != null) {
            Matcher m = pattern.matcher(line);
            if (m.find()) {
                cookie = line.substring(7, line.length());
            }
        }
        conn.disconnect();

        if (cookie == null) {
            throw new Exception();
        }

        return "enc=" + cookie;
    }

}